package com.lagou.edu.interceptor;

import com.lagou.edu.session.SessionStorage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private SessionStorage sessionStorage;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        String username = (String)request.getSession().getAttribute("username");
        boolean hasSession = sessionStorage.hasSession(username);
        if (!hasSession) {
            response.sendRedirect("/login.jsp");
        }
        return hasSession;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
        Object username = request.getSession().getAttribute("username");
        request.getSession().setAttribute("username", username);
    }
}
